<template>
    <div id="app" v-if="appInit">
        <div style="max-width: 750px;margin: 0 auto;">
            <index></index>
        </div>
    </div>
</template>

<script>
    import Index from './components/Index';
    import {mapState} from 'vuex';
    import {getQueryVariable, isJSON} from "./utils/public";
    import service from "./utils/request";
    import wx from 'weixin-js-sdk';
    import { Dialog, Toast } from 'vant';
    import {Storage} from "./utils/localstorage";

    export default {
        name: 'app',
        computed:{
            ...mapState(['common','users']),
        },
        components: {
            Index,
        },
        data(){
            return{
                appInit:false,
                storage:{},
            }
        },
        async created(){
            let that = this;

            // 初始化storage
            this.storage = new Storage();


            let env = process.env.VUE_APP_ENV;
            if(env === 'development'){
                // 测试环境直接认证通过，不能使用jssdk
                service.defaults.headers["We-Token"] = process.env.VUE_APP_DEFAULT_WE_TOKEN;
                // 定位
                that.common.address.adcode = '110114';
                that.common.address.province = '北京市';
                that.common.address.district = '昌平区';
                this.appInit = true;
            } else {
                Toast.loading({
                    message: '加载中...',
                    forbidClick: true,
                    duration: 0,
                });
                // 验证微信登录
                await this.verify();
                // 验证sdk
                await this.sdk();
                // 验证是否是微信浏览器
                let ua = window.navigator.userAgent.toLowerCase();
                that.common.wechat = ua.match(/MicroMessenger/i) && true;
                Toast.clear();
                this.appInit = true;
            }
        },
        methods:{
            verify(){
                let that = this;
                return new Promise((resolve, reject) => {

                    // 先检查本地有没有这个token
                    let token =localStorage.getItem('token');
                    console.log(token);

                    if(isJSON(token)){// 如果是普通storage删除掉（老数据）
                        console.log('有效缓存');
                        token = that.storage.getItem('token');
                        console.log(token);
                    } else {
                        console.log('清理缓存');
                        localStorage.removeItem('token');
                        token = null;
                    }

                    // 如果有code，验证完成后添加token
                    let code = getQueryVariable('code');

                    if(token){ // 如果本地token没过期，直接添加header就行了
                        service.defaults.headers["We-Token"] = token;
                        resolve();
                    } else if (code) {
                        // 请求openid
                        that.post('/api/client/auth/token', {code: code}).then(result => {
                            if (result.code === 0) {
                                // 增加token
                                that.storage.setItem({
                                    name:'token',
                                    value:result.data.token,
                                    expires:7 * 24 * 60 * 60 * 1000, // 有效期7天
                                })
                                service.defaults.headers["We-Token"] = result.data.token;
                                resolve();
                            } else {
                                Dialog.alert({message: result.msg}).then(()=>{location.replace('/')});
                                resolve();
                            }
                        }).catch(e=>{
                            Toast('登录失败，请稍后再试');
                            console.log(e);
                            switch (e) {
                                case 503: // 维护中
                                    console.log('code:503');
                                    // window.location.replace(process.env.VUE_APP_URL);
                                    break;
                            }
                        });
                    } else {
                        // 没有token和code，跳转授权登录
                        let appid = process.env.VUE_APP_ID;
                        let url = window.location.href;
                        let wechatUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' +
                            encodeURIComponent(url) + '&response_type=code&scope=snsapi_userinfo#wechat_redirect';
                        location.replace(wechatUrl);
                        reject();
                    }
                });
            },
            sdk() {
                let that = this;
                return new Promise((resolve, reject) => {
                    // 记录进入app时的url
                    if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
                        window.entryUrl = location.href.split('#')[0];
                    }
                    // 进行签名的时候  Android 不用使用之前的链接， ios 需要
                    that.common.entryUrl =  window.entryUrl;
                    // 接入jssdk
                    that.post('/api/common/jsapi',{url:/(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl}).then(result=>{
                        if(result.code === 0){
                            wx.config(result.data);
                        }
                    });
                    wx.ready(function () {

                        wx.updateAppMessageShareData({
                            title: '来飞网霸王餐', // 分享标题
                            desc: '天了噜，全城的免费活动都在这里啦！还不来？', // 分享描述
                            link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: 'http://lf-public.oss-cn-shenzhen.aliyuncs.com/upload/logo.jpg', // 分享图标
                            success: function () {
                                // 设置成功
                            }
                        })

                        wx.updateTimelineShareData({
                            title: '来飞网霸王餐', // 分享标题
                            link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: 'http://lf-public.oss-cn-shenzhen.aliyuncs.com/upload/logo.jpg', // 分享图标
                            success: function () {
                                // 设置成功
                            }
                        })

                        wx.getLocation({
                            type: 'gcj02', // 火星坐标
                            success: res => {
                                if (!res.longitude) {
                                    this.$dialog({message: '地址信息查询失败，请打开手机的定位功能后重新打开当前页面'});
                                    return;
                                }
                                that.post('/api/common/amap/regeo', res).then(result => { // 记录并解析地址
                                    if (result.code === 0) {
                                        that.common.address = result.data.regeocode.addressComponent;
                                        console.log(that.common.address);
                                        resolve();
                                    }
                                }).catch(e => {
                                    console.log('服务异常');
                                    console.log(e);
                                });
                            },
                            fail: res => {
                                this.$dialog({message: '地址授权失败，已将您的地址自动设置为北京市朝阳区'});
                                that.common.address.adcode = '110105';
                                that.common.address.province = '北京市';
                                that.common.address.district = '朝阳区';
                                console.log(res);
                            }
                        });
                    });
                    wx.error(function (res) {
                        console.log('服务异常');
                        console.log(res);
                        resolve();
                    });
                });
            },
        }
    }
</script>

<style>
    #app {
        font-family: 'Avenir', Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        color: #2c3e50;
    }
</style>
